<template>
    <view class="login-page">
        <button v-if="!userShow" @click="wxLogin">
            授权
        </button>
        <!-- 授权登录按钮 -->
        <view class="user" v-if="userShow">
            <!-- 底图 - 开始 -->
            <image class="user-header-image" :src="'https://source.unsplash.com/random/1920x1080?star,night'"></image>
            <!-- 底图 - 结束 -->

            <!-- 用户信息 - 开始 -->
            <view class="user-info-box">
                <image :src="user.avatar ? user.avatar : user_avg" shape="square" style="height: 80rpx;width: 120rpx;">
                </image>
                <view class="user-info-right">
                    <view class="user-nickname">{{ user.username ? user.username : user_name }}</view>
                    <view class="user-phone">
                        <image src="https://v2.jinrishici.com/one.svg" style="height: 30rpx;margin-top: 20rpx;"></image>
                    </view>
                </view>
            </view>
            <!-- 用户信息 - 结束 -->

            <!-- 充值优惠 - 开始 -->
            <view class="user-recharge-wrapper" style="text-align: center;padding: 50rpx;"
                @click="tz('/subPages/pages/map/index?openid=' + openid)">

                {{ address }}
            </view>
            <!-- 充值优惠 - 结束 -->

            <!-- 列表菜单 - 开始 -->
            <view class="user-activity-menu">
                <view class="menu-item" @click="tz('/subPages/pages/task/index?openid=' + openid)">
                    <view class="left">
                        <image class="menu-icon"
                            src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E6%8F%90%E9%86%92.png"></image>
                        <view class="menu-name">提醒代办</view>
                    </view>
                    <view class="menu-number text-red-500">{{ list.length }}</view>
                </view>
                <view class="menu-item" @click="tz('/subPages/pages/gpt/index?openid=' + openid)">
                    <view class="left">
                        <image class="menu-icon"
                            src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E5%95%8A.jpg">
                        </image>
                        <view class="menu-name">搜索问答</view>
                    </view>

                </view>
                <view class="menu-item" @click="tz('/subPages/pages/card/index?openid=' + openid)">
                    <view class="left">
                        <image class="menu-icon"
                            src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E9%93%B6%E8%A1%8C%E5%8D%A1.png">
                        </image>
                        <view class="menu-name">文件备忘</view>
                    </view>

                </view>
                <view class="menu-item" @click="tz('/subPages/pages/video/index?openid=' + openid)">
                    <view class="left">
                        <image class="menu-icon"
                            src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E8%A7%86%E9%A2%91.png">
                        </image>
                        <view class="menu-name">视频去水印</view>
                    </view>

                </view>
                <view class="menu-item" @click="tz('/subPages/pages/compass/index?openid=' + openid)">
                    <view class="left">
                        <image class="menu-icon"
                            src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E6%96%B9%E4%BD%8D%E8%A7%92.png">
                        </image>
                        <view class="menu-name">司庚罗盘</view>
                    </view>
                    <view class="menu-number text-red-500">{{ area }}</view>
                </view>
                <view class="menu-item" v-if="user.tdid != null"
                    @click="tz('/subPages/pages/c/index?openid=' + openid)">
                    <view class="left">
                        <image class="menu-icon"
                            src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/menu2-%E4%BF%AE%E8%A1%8C.png">
                        </image>
                        <view class="menu-name">看板2.0</view>
                    </view>
                    <view class="menu-number"></view>
                </view>
                <view class="menu-item" @click="updateUser()">
                    <view class="left">
                        <image class="menu-icon"
                            src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/app%E7%89%88%E6%9C%AC%20.png">
                        </image>
                        <view class="menu-name">当前版本</view>
                    </view>
                    <view class="menu-number">{{ version }}</view>
                </view>
            </view>
            <!-- 列表菜单 - 结束 -->
        </view>
        <wx-user-info-modal v-model="showAuthorizationModal" @updated="updatedUserInfoEvent"></wx-user-info-modal>

    </view>
</template>

<script>

import WxUserInfoModal from '@/uni_modules/tuniaoui-wx-user-info/components/tuniaoui-wx-user-info/tuniaoui-wx-user-info.vue'

export default {
    components: { WxUserInfoModal },
    data() {
        return {
            showAuthorizationModal: false,
            show: false,

            userInfo: {
                avatarUrl: '',
                nickName: ''
            },
            openid: '',
            userShow: false,
            user: {},
            version: '1.0.0',
            user_avg: '',
            user_name: '',
            list: [],
            address: '',
            area: '',
            locationData: {}


        }
    },
    onLoad() {
        let _this = this
        uni.getSystemInfo({
            success: function (res) {
                console.log('res', res)
                _this.version = res.appVersion
            },
        })
        this.wxLogin();
        this.getLocation();
        var that = this;
        uni.onCompassChange(function (res) {
            // 计算应偏移度数
            var rotate = res.direction.toFixed(0)
            var area = parseInt(rotate / 90)
            var detailArea = rotate % 90
            that.rotate = rotate
            // console.log(res.direction.toFixed(0), rotate)
            if (rotate > 157 && rotate <= 202) {

                that.area = "南（S）"
                //that.detailArea = 90 - detailArea

            }
            else if (rotate > 112 && rotate <= 157) {

                that.area = "东南（SE）"


            }
            else if (rotate > 202 && rotate <= 247) {

                that.area = "西南（SW）"


            }
            else if ((rotate > 337 && rotate <= 360) || (rotate > 0 && rotate <= 22)) {

                that.area = "北（N）"


            }
            else if (rotate > 22 && rotate <= 67) {

                that.area = "东北（NE）"


            }
            else if (rotate > 292 && rotate <= 337) {

                that.area = "西北（NW）"


            }
            else if (rotate > 67 && rotate <= 112) {

                that.area = "东（E）"

            } else if (rotate > 247 && rotate <= 292) {


                that.area = "西（W）"


            }
            that.area += "-" + rotate;
        });
        this.s();

        console.log('that.user', that.user)
    },
    methods: {
        s() {
            let that = this
            var header = 'Authorization:Bearer ' + that.user.gptKey + ';' + 'Content-Type:application/json';
            uni.request({
                url: 'https://zhangteng.cloud:5001/api/mainControllers/CallApiAsync', // 请求地址
                method: 'POST',
                data: {
                    url: 'https://chatapi.onechat.fun/v1/dashboard/billing/subscription', // 请求地址
                    data: "",
                    headers: header,
                    method: 'POST',
                },
                header: {
                    'content-type': 'application/x-www-form-urlencoded' // 根据需要修改请求内容类型
                },
                success: (res) => {
                    console.log('res', res)

                },
                fail: (err) => {
                    reject(err);
                }
            });
        },
        getLocation() {
            uni.getLocation({
                type: 'wgs84',
                success: (res) => {
                    this.location = res;
                    console.log('当前位置的经度：' + res.longitude);
                    console.log('当前位置的纬度：' + res.latitude);
                    // 获取到经纬度后，调用解析位置的函数
                    this.getCityName(res.latitude, res.longitude);
                },
                fail: () => {
                    uni.showToast({
                        title: '获取位置失败',
                        icon: 'none'
                    });
                    //this.getInfo()
                }
            });
        },
        getCityName(latitude, longitude) {
            // 这里以腾讯地图为例，需要替换为你的腾讯地图API Key
            const apiKey = 'IXBBZ-HHSK3-UWW3K-3DB6K-M7Y5K-F4FM5';
            const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${apiKey}`;

            uni.request({
                url: url,
                success: (res) => {
                    console.log('getCityName', res)
                    if (res.data.status === 0) {
                        this.address = res.data.result.address;
                        const city = res.data.result.address_component.city;
                        this.city = city;
                        // this.getInfo()
                        console.log('当前城市：' + city);
                        this.defaultValue = [];
                        this.defaultValue.push(res.data.result.address_component.province)
                        this.defaultValue.push(res.data.result.address_component.city)
                        this.defaultValue.push(res.data.result.address_component.district)
                        console.log('this.defaultValue', this.defaultValue)

                        this.locationData = JSON.stringify(res.data.result);

                        uni.showToast({
                            title: `当前城市: ${city}`,
                            icon: 'none'
                        });
                    } else {
                        uni.showToast({
                            title: '解析城市失败',
                            icon: 'none'
                        });
                    }

                },
                fail: () => {
                    uni.showToast({
                        title: '请求失败',
                        icon: 'none'
                    });
                }
            });
        },
        updateUser() {
            this.user.locationData = this.locationData;
            console.log('updateUser', this.user)
            uni.request({
                url: "https://zhangteng.cloud:5001/api/NingLiUser/Update",
                data: this.user,
                method: "PUT",
                success: (res) => {
                    console.log('updateUser', res)
                    if (res.data) {
                        uni.showToast({
                            title: `登记成功`,
                            icon: 'none'
                        });
                    }
                    else {
                        uni.showToast({
                            title: `登记失败`,
                            icon: 'none'
                        });

                    }
                }
            });
        },
        openAuth() {
            console.log('openAuth')
            uni.requestSubscribeMessage({
                tmplIds: ['WSjNDldNqeCMYHivK2bITtFJT-F68y-AiKfabqfrV4A'],
                success: (res) => {
                    console.log('openAuth', res);
                }
            })
        },

        tz(url) {
            uni.navigateTo({
                url: url
            });
        },
        getCurrentDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const formattedDate = `${year}-${month}-${day}`;

            return formattedDate;
        },
        getTaskList(date) {
            uni.request({
                url: 'https://zhangteng.cloud:5001/api/CalendarList/GetOpenid/' + this.openid + "/" + date,

                success: (res) => {
                    console.log('getTaskList', res)
                    this.list = res.data;
                }
            })
        },
        // 打开获取用户信息弹框
        openAuthorizationModal() {
            this.showAuthorizationModal = true
        },

        // 获取到的用户信息
        updatedUserInfoEvent(info) {
            info.avatarUrl = 'data:image/jpeg;base64,' + wx.getFileSystemManager().readFileSync(info.avatar, 'base64')
            console.log('获取到的用户信息', info)
            uni.request({
                url: `https://zhangteng.cloud:5001/api/NingLiUser/Add`,
                method: "POST",
                data: {
                    openid: this.openid,
                    username: info.nickname,
                    avatar: info.avatarUrl,
                },
                success: (res) => {
                    console.log('res', res)
                    uni.request({
                        url: 'https://zhangteng.cloud:5001/api/NingLiUser/GetOpenid/' + this.openid,

                        success: (res2) => {
                            console.log('res2', res2)
                            // 5 判断该微信用户是否是系统中用户
                            if (res2.data != "no") {
                                this.user = res2.data;
                                uni.setStorageSync('user', this.user);
                                this.userShow = true;
                                this.showAuthorizationModal = false
                                this.getTaskList(this.getCurrentDate());
                            }
                            else {
                                this.showAuthorizationModal = true
                            }
                        }
                    })
                }
            });
        },
        wxLogin() {
            console.log('wxLogin')
            uni.login({
                provider: 'weixin',
                onlyAuthorize: true,
                success: (loginRes) => {
                    console.log('loginRes', loginRes)
                    if (loginRes.errMsg == 'login:ok') {
                        // 1 获得js_code
                        let js_code = loginRes.code
                        // 2 请求微信api 传递4个参数 appid secret js_code grant_type
                        uni.request({
                            url: 'https://zhangteng.cloud:5001/api/NingLiUser/Openid/' + js_code,

                            success: (res) => {
                                // 3 获得openid
                                console.log('jscode2session', res)
                                this.openid = res.data
                                // 4 openid提交给后端接口 伪代码
                                uni.request({
                                    url: 'https://zhangteng.cloud:5001/api/NingLiUser/GetOpenid/' + this.openid,

                                    success: (res2) => {
                                        console.log('GetOpenid', res2)


                                        // 5 判断该微信用户是否是系统中用户
                                        if (res2.data != "no") {
                                            this.user = res2.data;
                                            console.log('this.user1', this.user)
                                            this.userShow = true;
                                            uni.setStorageSync('user', this.user);
                                            // this.date = this.getCurrentDate();

                                            this.getTaskList(this.getCurrentDate());
                                        }
                                        else {
                                            this.showAuthorizationModal = true
                                        }
                                    }
                                })
                            }
                        })


                    }
                }
            })
        }


    }
}
</script>

<style>
page {
    background: #F4F4F4;
}
</style>

<style lang="scss">
.user {
    .user-header-image {
        width: 100%;
    }

    .user-info-box {
        background: #ffffff;
        padding: 30rpx;
        margin: -80rpx 20rpx 20rpx 20rpx;
        position: relative;
        border-radius: 20rpx;
        display: flex;
        align-items: center;

        .user-avg {
            width: 100rpx;
            height: 100rpx;
            border-radius: 10rpx;
        }

        .user-nickname {
            margin-left: 20rpx;
        }

        .user-phone {
            margin-left: 20rpx;
            font-size: 24rpx;
            color: #666666;
        }
    }

    .user-recharge-wrapper {
        background: #ffffff;
        border-radius: 20rpx;
        padding: 10rpx;
        margin: 20rpx;

        .user-recharge-box {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20rpx;

            .recharge-info {
                .info-title {
                    color: #333;
                    font-size: 28rpx;
                    font-weight: bold;
                }

                .info-content {
                    color: #999;
                    font-size: 24rpx;
                }
            }

            .recharge-button {
                // background: #ff4131;
                color: #333;
                padding: 10rpx 20rpx;
                font-size: 22rpx;
                border-radius: 50rpx;
                flex-shrink: 0;
                border: 1rpx solid #dadbde;
            }
        }

        .recharge-user-money {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 20rpx;
            font-size: 26rpx;
            color: #333;

            .recharge-money {
                font-weight: bold;
                font-size: 30rpx;
            }

            .recharge-money::first-letter {
                font-size: 22rpx;
            }
        }
    }

    .user-activity-menu {
        padding: 30rpx;
        margin: 20rpx;
        border-radius: 20rpx;
        background: #fff;

        .menu-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 60rpx;

            .left {
                display: flex;
                align-items: center;

                .menu-icon {
                    width: 40rpx;
                    height: 40rpx;
                }


                .menu-name {
                    font-size: 28rpx;
                    margin-left: 20rpx;
                    color: #333;
                }
            }

            .menu-number {
                font-size: 30rpx;
                color: #666666;
                letter-spacing: 2rpx;
            }
        }

        .menu-item:first-child {
            margin-top: 0;
        }
    }
}
</style>
